package com.vaadin.thomas.contenttool.ui;

import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.thomas.contenttool.data.Model;
import com.vaadin.thomas.contenttool.data.Value;
import com.vaadin.thomas.contenttool.ui.events.ValueAddedEvent;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;

public class AddValueWindow extends Window {

	private static final long serialVersionUID = -5055610445984242710L;
	private TextField valueNameField;

	public AddValueWindow(String selectedFragment, boolean isValueSelected) {

		setModal(true);
		setWidth(300, UNITS_PIXELS);
		setHeight(200, UNITS_PIXELS);
		center();

		valueNameField = new TextField(MainLayout.ct().get(
				"contenttool.addvalue.identifier"));
		valueNameField.setValue(selectedFragment);
		valueNameField.setWidth(100, UNITS_PERCENTAGE);
		addComponent(valueNameField);

		if (isValueSelected) {
			int index = selectedFragment.lastIndexOf(".") + 1;
			valueNameField.setSelectionRange(index, selectedFragment.length()
					- index);
		} else {
			valueNameField.setCursorPosition(selectedFragment.length());
		}

		Button addButton = new Button(MainLayout.ct().get(
				"contenttool.addvalue.add"));
		addButton.addListener(new AddListener());
		addButton.setClickShortcut(KeyCode.ENTER);
		addComponent(addButton);

		Button cancelButton = new Button(MainLayout.ct().get(
				"contenttool.addvalue.cancel"));
		cancelButton.addListener(new ClickListener() {

			private static final long serialVersionUID = -4853133554064442072L;

			@Override
			public void buttonClick(ClickEvent event) {
				close();
			}
		});
		addComponent(cancelButton);

	}

	private class AddListener implements ClickListener {

		private static final long serialVersionUID = 8962246112308294171L;

		@Override
		public void buttonClick(ClickEvent event) {
			String name = (String) valueNameField.getValue();

			if (name == null || name.equals("")) {
				return;
			}

			Value newValue = Model.get().addValue(name);
			MainLayout.bb().fire(new ValueAddedEvent(newValue));
			close();
		}
	}
}
